package com.doris.lucene.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.doris.lucene.Constants;
import com.doris.lucene.SearchWord;
import com.doris.lucene.SearchWordStat;

/**
 * 搜索词统计
 * 
 * @author root
 *
 */
public class SearchWordServlet extends HttpServlet {

	private static final long serialVersionUID = 3252013785385584079L;
	/**
	 * 当前页
	 */
	private static final String CURRENT_PAGE = "currentPage";

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Map<String, Integer> map = SearchWordStat.getSingleton().getMap();
		List<Map.Entry<String, Integer>> entrys = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(entrys, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return o2.getValue() - o1.getValue();
			}
		});

		List<SearchWord> results = new ArrayList<SearchWord>();
		String page = request.getParameter(CURRENT_PAGE);
		Integer currentPage = page != null ? Integer.valueOf(page) : 1;
		request.setAttribute(CURRENT_PAGE, currentPage);
		request.setAttribute("total", map.size());
		request.setAttribute("totalPages", (map.size() - 1) / Constants.NUM_PER_PAGE + 1);
		int start = (currentPage - 1) * Constants.NUM_PER_PAGE;
		int end = Math.min(map.size(), currentPage * Constants.NUM_PER_PAGE);
		for (int i = start; i < end; i++) {
			Map.Entry<String, Integer> entry = entrys.get(i);
			results.add(new SearchWord(i + 1, entry.getKey(), entry.getValue()));
		}
		request.setAttribute("results", results);
		request.getRequestDispatcher("searchWordResult.jsp").forward(request, response);
	}

}
